package com.fingard.dsp.bank.directbank.citic05;

import com.alibaba.fastjson.JSONObject;
import com.citic.openbank.configuration.OpenBankSdkConfiguration;
import com.citic.openbank.sdk.AppException;
import com.citic.openbank.sdk.CiticSdk;
import com.citic.openbank.sdk.CiticSdkInterface;
import com.citic.openbank.sdk.RequestHeader;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

//import static com.fingard.dsp.bank.directbank.citic05.util.API.*;
import static com.yeepay.g3.sdk.yop.client.AbstractClient.getHttpClient;


public class CITIC05Base extends DirectBase {
    private static TransIDHelper idHelper = new TransIDHelper(1, 999);

    protected String getQryTransID() {
        Date tmpDateNow = new Date();
        return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
    }

    protected String getCharset() {
        return getBankConfig().getCharset("UTF-8");
    }

    protected void writeCommonHeader(RequestHeader header, CITIC05Header p_bankHeader, ActSetItem actItem) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.openTransCode)) {
            throw new Exception("未赋值openTransCode");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.openMerFlowId)) {
            throw new Exception("未赋值openMerFlowId");
        }
        header.setOpenVer("1.0.0");
        header.setOpenTransCode(p_bankHeader.openTransCode);
        header.setOpenMerCode(actItem.merchantId);
        header.setOpenMerName(actItem.userCode);
        header.setOpenBusiType(actItem.busCode);
        header.setOpenLaunchDate(Format.Date8Format.format(new Date()));
        header.setOpenLaunchTime(Format.Time6Format.format(new Date()));
        header.setOpenMerFlowId(p_bankHeader.openMerFlowId);
    }

    protected void writeCommonHeader1(JSONObject jsonRequest, CITIC05Header p_bankHeader, ActSetItem actItem) throws Exception {
        if (StringHelper.isNullOrEmpty(p_bankHeader.openTransCode)) {
            throw new Exception("未赋值openTransCode");
        }
        if (StringHelper.isNullOrEmpty(p_bankHeader.openMerFlowId)) {
            throw new Exception("未赋值openMerFlowId");
        }
        jsonRequest.put("OPENVER", "1.0.0");
        jsonRequest.put("OPENTRANSCODE", p_bankHeader.openTransCode);
        jsonRequest.put("OPENMERCODE", actItem.merchantId);
        jsonRequest.put("OPENMERNAME", actItem.userCode);
        jsonRequest.put("OPENBUSITYPE", actItem.busCode);
        jsonRequest.put("OPENLAUNCHDATE", Format.Date8Format.format(new Date()));
        jsonRequest.put("OPENLAUNCHTIME", Format.Time6Format.format(new Date()));
        jsonRequest.put("OPENMERFLOWID", p_bankHeader.openMerFlowId);
    }

//    protected String sendToBank(RequestHeader header, String reqBody, ActSetItem actItem) throws Exception {
//        String reqJson = null;
//
//        try {
//            reqJson = buildReqJson(header, reqBody, actItem);
//            WriteBankLogLn2("请求报文密文: " + reqJson);
//        } catch (Exception var17) {
//            WriteBankLogLn("build ReqJson error", var17);
//            throw new AppException("IF01001", var17);
//        }
//
//        HttpClient httpClient = getHttpClient();
//
//        HttpPost httpPost = new HttpPost(bankFront.serverURL);
//        StringEntity se = null;
//
//        try {
//            se = new StringEntity(reqJson);
//        } catch (UnsupportedEncodingException var14) {
//            WriteBankLogLn("unsupport encoding ", var14);
//            throw new AppException("IF01004", var14);
//        }
//
//        se.setContentType("text/json");
//        se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
//        httpPost.setEntity(se);
//        HttpResponse resp = null;
//
//        try {
//            resp = httpClient.execute(httpPost);
//        } catch (IOException var13) {
//            WriteBankLogLn("httpclient execute error ", var13);
//            throw new AppException("IF01005", var13);
//        }
//
//        String respJson = null;
//
//        try {
//            respJson = EntityUtils.toString(resp.getEntity(), getCharset());
//        } catch (IOException var12) {
//            WriteBankLogLn("encoding response error  ", var12);
//            throw new AppException("IF01006", var12);
//        }
//
//        WriteBankLogLn("响应报文密文: " + respJson);
//        String realRespJson = null;
//        if ((realRespJson = validateSignature(respJson, actItem)) == null) {
//            WriteBankLogLn("验签失败!!");
//            return null;
//        } else {
//            WriteBankLogLn2("响应报文明文: " + realRespJson);
//            return realRespJson;
//        }
//    }

//    protected String buildReqJson(RequestHeader header, String reqBody, ActSetItem actItem) throws Exception {
//        if (header.getOpenMerFlowId() != null && !"".equals(header.getOpenMerFlowId())) {
//            if (header.getOpenTransCode() != null && !"".equals(header.getOpenTransCode())) {
//                String reqFormat = "{\n \"OPENVER\": \"%s\",\n \"OPENTRANSCODE\": \"%s\",\n \"OPENMERCODE\": \"%s\",\n \"OPENMERNAME\": \"%s\",\n \"OPENBUSITYPE\": \"%s\",\n \"OPENLAUNCHDATE\": \"%s\",\n \"OPENLAUNCHTIME\": \"%s\",\n \"OPENMERFLOWID\": \"%s\",\n \"txCode\": \"%s\",\n %s\n}\n";
//                if (reqBody == null || "".equals(reqBody.trim()) || "{}".equals(reqBody.trim())) {
//                    reqBody = "{\"__blank_body__\": \"\"}";
//                }
//                reqBody = reqBody.substring(reqBody.indexOf(123) + 1, reqBody.lastIndexOf(125));
//                DateFormat yyyyMMdd = new SimpleDateFormat("yyyyMMdd");
//                DateFormat HHmmss = new SimpleDateFormat("HHmmss");
//                String reqJson = String.format(reqFormat, header.getOpenVer(), header.getOpenTransCode(), header.getOpenMerCode(), header.getOpenMerName(), header.getOpenBusiType(), header.getOpenLaunchDate(), header.getOpenLaunchTime(), header.getOpenMerFlowId(), header.getOpenTransCode(), reqBody);
//                WriteBankLogLn2("请求报文明文: " + reqJson);
//                String encryptBusiness = null;
//                String signData = null;
//                signData = signature(reqJson, actItem);
//                encryptBusiness = encryptBusiness(reqJson, actItem);
//                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject("{}");
//                jsonObject.put("encryptBody", encryptBusiness);
//                jsonObject.put("sign", signData);
//                return jsonObject.toString();
//            } else {
//                throw new IllegalArgumentException("交易码不得为空");
//            }
//        } else {
//            throw new IllegalArgumentException("商户流水号不得为空");
//        }
//    }

    protected String sendToBank1(String tmpReqStr, String serverUrl) throws Exception {
        WriteBankLogLn2("请求提交服务地址：" + serverUrl);
        String retStr = null;
        URL url = null;
        HttpURLConnection conn = null;
        OutputStream outStream = null;
        InputStream inStream = null;
//        URLConnection conn = null;
        try {
            url = new URL(serverUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (url.getProtocol().equals("https")) {
                HttpsURLConnection con = (HttpsURLConnection) conn;
                TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkClientTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }

                    public void checkServerTrusted(
                            java.security.cert.X509Certificate[] certs, String authType) {
                    }
                }};
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, trustAllCerts, new java.security.SecureRandom());
                con.setSSLSocketFactory(sc.getSocketFactory());
                con.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String arg0, SSLSession arg1) {
                        return true;
                    }
                });
            }
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("connection", "keep-alive");
            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.connect();

            // 发送请求
            outStream = conn.getOutputStream();
            outStream.write(tmpReqStr.getBytes("UTF-8"));
            outStream.flush();

            // 获取响应结果
            inStream = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(inStream));
            String respstr = null;
            StringBuilder sbr = new StringBuilder();
            while ((respstr = br.readLine()) != null) {
                sbr.append(respstr);
            }
            br.close();

            //解构出encryptBody和sign
            JSONObject jsonObject = JSONObject.parseObject(sbr.toString());
            String encryptBody = jsonObject.getString("encryptBody");
//            String sign = jsonObject.getString("sign");
            retStr = encryptBody;
            WriteBankLogStep3(retStr);

        } catch (Exception ex) {
            WriteBankLogLn(ex);
        } finally {
            try {
                if (inStream != null) inStream.close();
            } catch (Exception e) {
                WriteBankLogLn(e);
            }
            try {
                if (outStream != null) outStream.close();
            } catch (Exception e) {
                WriteBankLogLn(e);
            }
            try {
                if (conn != null) conn.disconnect();
            } catch (Exception e) {
                WriteBankLogLn(e);
            }
        }
        return retStr;
    }


    // 设置密钥
    protected void setKeys(CiticSdkInterface sdk, ActSetItem actItem) throws Exception {
        sdk.setPrivateKeyDecryptWithPwdUseStr(actItem.ownKeyStorePath,actItem.ownKeyPassword);
        sdk.setPrivateKeySignatureWithPwdUseStr(actItem.ownKeyStorePath,actItem.ownKeyPassword);
        sdk.setPublicKeyEncryptUseStr(actItem.oppCertFilePath);
        sdk.setPublicKeyValidateSignatureUseStr(actItem.oppCertFilePath);
    }

    // 设置交易公共参数
    protected void setConfiguration(CiticSdkInterface sdk, ActSetItem actItem) throws Exception {
        sdk.setConnectionTimeout(30000);
        sdk.setOpenBusiType(actItem.busCode);
        sdk.setOpenMerCode(actItem.merchantId);
        sdk.setOpenMerName(actItem.userCode);
        sdk.setOpenVer("1.0.0");
        sdk.setPublicUrl(bankFront.serverURL);
        sdk.setTransferEncode(getCharset());
    }

}